package com.ruoyi.warn.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.ruoyi.common.constant.BusinessConstant;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.warn.domain.bo.AssessBo;
import com.ruoyi.warn.domain.vo.AssessNumsVo;
import com.ruoyi.warn.domain.vo.UnitKpiVo;
import com.ruoyi.warn.domain.vo.ZbxqVo;
import com.ruoyi.warn.domain.vo.ZhpmVo;
import com.ruoyi.warn.service.IAssessService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.compress.utils.Lists;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

/**
 * @author zhangxiaohao
 * @comment 毒品问题治理考核统计
 * @date 2023/4/13
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/assess")
public class AssessController {

    private final IAssessService assessService;
    private final ISysDeptService deptService;

    /*
     * 数量统计
     */
    @GetMapping("/nums")
    public R<AssessNumsVo> nums() {
        return R.ok(assessService.nums());
    }

    /*
     * 综合排名
     */
    @GetMapping("/zhpm")
    public R<List<ZhpmVo>> zhpm(AssessBo query) {
        List<ZhpmVo> list = Lists.newArrayList();
        // 构建条件
        buildQuery(query);
        String start = query.getStart();
        String end = query.getEnd();
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        if (CollUtil.isNotEmpty(depts)) {
            depts.forEach(dept -> {
                UnitKpiVo currentUnitKpi = assessService.getUnitKpiVo(dept.getDeptId(), start, end);
                ZhpmVo zhpm = new ZhpmVo();
                zhpm.setDw(dept.getDeptName());
                // 综合分值
                BigDecimal currentScore = assessService.getScore(currentUnitKpi);
                zhpm.setZhfz(currentScore.toString());
                // 环比: 选择时间段内数据/上一该时长时间段内数据*100%
                Integer day = Convert.toInt(DateUtil.betweenDay(DateUtil.parseDate(start), DateUtil.parseDate(end), true));
                DateTime beforeDate = DateUtil.offsetDay(DateUtil.parseDate(start), day);
                UnitKpiVo beforeUnitKpiVo = assessService.getUnitKpiVo(dept.getDeptId(), beforeDate.toString(), start);
                BigDecimal beforeScore = assessService.getScore(beforeUnitKpiVo);
                String hb;
                if (currentScore.compareTo(BigDecimal.ZERO) == 0 || beforeScore.compareTo(BigDecimal.ZERO) == 0) {
                    hb = "0.00";
                } else {
                    hb = currentScore.divide(beforeScore, 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100)).toString();
                }
                zhpm.setHb(hb);
                list.add(zhpm);
            });
        }
        return R.ok(list);
    }

    /**
     * 综合排名 - 列表导出
     */
    @PostMapping("/zhpm/export")
    public void zhpmExport(AssessBo query, HttpServletResponse response) {
        List<ZhpmVo> list = this.zhpm(query).getData();
        ExcelUtil.exportExcel(list, "综合排名", ZhpmVo.class, response);
    }

    /**
     * 曲线 - 指标详情
     */
    @GetMapping("/zbxq")
    public R<List<ZbxqVo>> zbxq(AssessBo query) {
        // 构建条件
        buildQuery(query);
        String type = query.getType();
        List<ZbxqVo> list = Lists.newArrayList();
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        if (CollUtil.isNotEmpty(depts)) {
            for (SysDept dept : depts) {
                UnitKpiVo unitKpi = assessService.getUnitKpiVo(dept.getDeptId(), query.getStart(), query.getEnd());
                BigDecimal rate = BigDecimal.ZERO;
                if (unitKpi != null) {
                    switch (type) {
                        case BusinessConstant.AssessKpiType.GKL:
                            // 管控率
                            rate = unitKpi.getGkl();
                            break;
                        case BusinessConstant.AssessKpiType.ZXL:
                            // 执行率
                            rate = unitKpi.getZxl();
                            break;
                        case BusinessConstant.AssessKpiType.QDL:
                            // 签到率
                            rate = unitKpi.getQdl();
                            break;
                        case BusinessConstant.AssessKpiType.NJL:
                            // 尿检率
                            rate = unitKpi.getNjl();
                            break;
                        case BusinessConstant.AssessKpiType.THL:
                            // 谈话率
                            rate = unitKpi.getThl();
                            break;
                        case BusinessConstant.AssessKpiType.JFL:
                            // 家访率
                            rate = unitKpi.getJfl();
                            break;
                        case BusinessConstant.AssessKpiType.JYAZL:
                            // 就业安置率
                            rate = unitKpi.getJyazl();
                            break;
                        case BusinessConstant.AssessKpiType.BFL:
                            // 帮扶率
                            rate = unitKpi.getBfl();
                            break;
                        case BusinessConstant.AssessKpiType.XCXAZL:
                            // 小程序安装率
                            rate = unitKpi.getXcxazl();
                            break;
                        default:
                            return R.fail("未知指标类型");
                    }
                }
                ZbxqVo vo = new ZbxqVo();
                vo.setName(dept.getDeptName());
                vo.setRate(rate);
                list.add(vo);
            }
        }
        return R.ok(list);
    }

    /**
     * 构造时间段
     * @param query 条件
     */
    private void buildQuery(AssessBo query) {
        String type = query.getType();
        if (StringUtils.isBlank(type)) {
            query.setType(BusinessConstant.AssessKpiType.GKL);
        }
        String interval = query.getInterval();
        DateTime date = DateUtil.date();
        String current = DateUtil.format(date, "yyyy-MM-dd");
        if (CharSequenceUtil.isBlank(query.getStart()) || CharSequenceUtil.isBlank(query.getEnd())) {
            query.setStart(current);
            query.setEnd(current);
        }
        if (StringUtils.isNotEmpty(interval)) {
            switch (interval) {
                case "0":
                    // 今日
                    query.setStart(current);
                    query.setEnd(current);
                    break;
                case "1":
                    // 近一周
                    query.setStart(DateUtil.beginOfWeek(date).toString());
                    query.setEnd(DateUtil.endOfWeek(date).toString());
                    break;
                case "2":
                    // 近一月
                    query.setStart(DateUtil.beginOfMonth(date).toString());
                    query.setEnd(DateUtil.endOfMonth(date).toString());
                    break;
                default:
                    break;
            }
        }
    }
}
